package com.mobimagic.lockscreen.view;

import java.util.Observable;
import java.util.Observer;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.mobimagic.lockscreen.AppEnv;
import com.mobimagic.lockscreen.Charge;
import com.mobimagic.lockscreen.Charge.ChargingValueType;
import com.mobimagic.lockscreen.R;
import com.mobimagic.lockscreen.report.StatKey;
import com.mobimagic.lockscreen.sdk.ILockScreenCommon;
import com.mobimagic.lockscreen.sdk.LockScreenSDK;
import com.mobimagic.lockscreen.util.ScreenUtil;
import com.mobimagic.lockscreen.view.MobileChargingScrollView.OnMobileScrollViewScroll;
import com.mobimagic.lockscreen.view.MobileChargingScrollView.ScrollInfo;
import com.mobimagic.lockscreen.view.MobileChargingView.CardType;

public class MobileChargingBGView extends View implements Observer, OnMobileScrollViewScroll {
    public static final boolean SAVE_MODE = true;
    private static final String TAG = "MobileChargingBGView";
    private static final boolean DEBUG = AppEnv.bAppdebug;
    private Charge charge;
    private Wave wave1, wave2;
    //    private Bubbles bubbles;
    private Paint paint;
    private int topGap = 0;
    private int bottomGap = 0;
    private ChargingProgress chargingProgress;

    /**
     * 峰值
     */
    private int peak;

    /**
     * 水平线
     */
    private int levelY;

    private TopFadeView topFadeView;
    private FadeBitmapHelper fadeBitmapHelper;
    private boolean isOval1Contains;
    private boolean isOval2Contains;
    private boolean isOval3Contains;
    private PopupWindow popupWindow;
    private float radus;
    private Handler mHandler;
    private Float scale;
    private Runnable runnable;
    private RectF oval1;
    private RectF oval2;
    private RectF oval3;
    private ILockScreenCommon mLockScreenCommon;

    public void onStop() {
        wave1.onStop();
        wave2.onStop();
        //        bubbles.onStop();
    }

    public void onStart() {
        wave1.onStart();
        wave2.onStart();
        //        bubbles.onStart();
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        fadeBitmapHelper = new FadeBitmapHelper(getContext().getResources());
    }

    public void setTopFadeView(TopFadeView topFadeView) {
        this.topFadeView = topFadeView;
    }

    public Charge getCharge() {
        return charge;
    }

    public void setCharge(Charge charge) {
        this.charge = charge;
        setWaveLevel();
        postInvalidate();
        chargingProgress.setCharge(charge);
        //        bubbles.setCharge(charge);
    }

    public MobileChargingBGView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mLockScreenCommon = LockScreenSDK.getInstance().getLockScreenCommon();
        this.peak = LayoutData.getInstance().getPeakHeight();
        this.bottomGap = peak * 2 + LayoutData.getInstance().getSlidLockHeight();
        this.topGap = LayoutData.getInstance().getWaveTop();

        wave1 = new Wave(peak, 0, this);
        wave2 = new Wave(peak, 0.3f, null);
        //        bubbles = new Bubbles(this);
        //        bubbles.setTopGap(topGap);
        //        bubbles.setBottomGap(bottomGap);

        float ringWidth = getResources().getDimension(R.dimen.charging_progress_ring_width);
        radus = getResources().getDimension(R.dimen.charging_progress_radus);
        float lineLength = getResources().getDimension(R.dimen.charging_progress_line);
        float marginBottom = getResources().getDimension(R.dimen.charging_progress_margin_bottom);
        float lineWidth = getResources().getDimension(R.dimen.charging_progress_line_width);
        paint = new Paint();
        paint.setAntiAlias(true);
        chargingProgress = new ChargingProgress(ringWidth, radus, lineLength, marginBottom, lineWidth, paint);
        chargingProgress.setTopGap(topGap);

        Bitmap b1 = getBitmap(R.drawable.card_battery_view);
        Bitmap b2 = getBitmap(R.drawable.icon_continuation);
        Bitmap b3 = getBitmap(R.drawable.icon_trickle);
        chargingProgress.setBitmaps(b1, b2, b3);
        mHandler = new Handler();
    }

    public ChargingProgress getChargingProgress() {
        return chargingProgress;
    }

    private Bitmap getBitmap(int res) {
        Drawable drawable = getResources().getDrawable(res);
        if (drawable instanceof BitmapDrawable) {
            BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
            return bitmapDrawable.getBitmap();
        }

        return null;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = MeasureSpec.getSize(heightMeasureSpec);
        setMeasuredDimension(width, height);
        //        bubbles.setBounds(width, height);
        generatePath();
    }

    private void generatePath() {
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        chargingProgress.setBounds(width, height);
        //两个生命周期  4*waveLength=1周期
        wave1.generatePath(width, height);
        wave2.generatePath(width, height);
        setWaveLevel();
    }

    @Override
    public void invalidate(Rect dirty) {
        super.invalidate(dirty);
    }

    public int getTopGap() {
        return topGap;
    }

    public void setTopGap(int topGap) {
        this.topGap = topGap;
        chargingProgress.setTopGap(topGap);
        //        bubbles.setTopGap(topGap);
    }

    private void setWaveLevel() {
        if (charge == null) {
            return;
        }
        int height = getMeasuredHeight();
        int full = height - topGap - bottomGap;
        levelY = topGap + (int) (full - charge.getChargingValue() * (full));
        wave1.setLevelY(levelY);
        wave2.setLevelY(levelY);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        wave1.draw(canvas, paint);
        wave2.draw(canvas, paint);
        //        bubbles.draw(canvas);
        chargingProgress.draw(canvas, paint, wave1, wave2);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        Canvas fadeCanvas = fadeBitmapHelper.preDraw(getMeasuredWidth(), getMeasuredHeight());
        if (fadeCanvas != null) {
            super.draw(fadeCanvas);
            Bitmap bitmap = fadeBitmapHelper.endDraw();
            if (bitmap != null) {
                topFadeView.setBgBitmap(bitmap);
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        scale = chargingProgress.getCurrentScale();
        Float x = event.getX();
        Float y = event.getY();
        oval1 = chargingProgress.getOval_1();
        oval2 = chargingProgress.getOval_2();
        oval3 = chargingProgress.getOval_3();
        if (oval1 == null || oval2 == null || oval3 == null) {
            return false;
        }
        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            if (oval1.contains(x, y)) {
                isOval1Contains = true;
                return true;
            }
            if (oval2.contains(x, y)) {
                isOval2Contains = true;
                return true;
            }
            if (oval3.contains(x, y)) {
                isOval3Contains = true;
                return true;
            }
            return false;
        case MotionEvent.ACTION_UP:
            checkIsInitPop(x, y);
            break;
        default:
            break;
        }
        return true;
    }

    private void checkIsInitPop(Float x, Float y) {
        if (isOval1Contains && oval1.contains(x, y) && scale == 1) {
            initPopupWindow(oval1, true);
        }
        if (isOval2Contains && oval2.contains(x, y) && scale == 1) {
            initPopupWindow(oval2, true);
        }
        if (isOval3Contains && oval3.contains(x, y) && scale == 1) {
            initPopupWindow(oval3, true);
        }
        isOval1Contains = isOval2Contains = isOval3Contains = false;
    }

    void initPopupWindow(RectF oval, boolean isClickOval) {
        if (runnable != null) {
            mHandler.removeCallbacks(runnable);
        }
        removePop();
        FrameLayout layout = (FrameLayout) LayoutInflater.from(getContext()).inflate(
                R.layout.mobile_charge_tip_popupwindow, null);
        TextView tips = (TextView) layout.findViewById(R.id.charging_tips);
        ImageView pointer = (ImageView) layout.findViewById(R.id.pointer_image);
        int curChargeValueType = 0;
        if (oval == chargingProgress.getOval_1()) {
            tips.setText(R.string.fast_charge_tips);
            curChargeValueType = 1;
        } else if (oval == chargingProgress.getOval_2()) {
            tips.setText(R.string.continuous_charging_tips);
            curChargeValueType = 2;
        } else if (oval == chargingProgress.getOval_3()) {
            tips.setText(R.string.trickle_charging_tips);
            curChargeValueType = 3;
        }
        if (isClickOval) {
            mLockScreenCommon.dbLog(StatKey.STATISTIC_MOBILE_CLICK_POPUP_CHARGE_INSTRUC, curChargeValueType);
        } else {
            mLockScreenCommon.dbLog(StatKey.STATISTIC_MOBILE_AUTO_POPUP_CHARGE_INSTRUC, curChargeValueType);
        }
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) pointer.getLayoutParams();
        int circleWidth = ScreenUtil.dpToPxInt(getContext(), 2);
        params.leftMargin = (int) (oval.left + 2 * circleWidth);
        pointer.setLayoutParams(params);
        Resources resources = LockScreenSDK.getInstance().getContext().getResources();
        int popWidth = ScreenUtil.getScreenWidth(getContext()) - 2
                * resources.getDimensionPixelSize(R.dimen.title_bar_padding);
        int popHeight = resources.getDimensionPixelSize(R.dimen.boost_charge_pop_h);
        popupWindow = new PopupWindow(layout, popWidth, popHeight);
        popupWindow.setFocusable(false);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(this, Gravity.TOP, 0, (int) (oval.top - popHeight));
        runnable = new Runnable() {
            @Override
            public void run() {
                removePop();
            }
        };
        mHandler.postDelayed(runnable, 4000);
    }

    public void removePop() {
        if (popupWindow != null && popupWindow.isShowing()) {
            popupWindow.dismiss();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        wave1.onAttachedToWindow();
        wave2.onAttachedToWindow();
        //        bubbles.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        wave1.onDetachedFromWindow();
        wave2.onDetachedFromWindow();
        //        bubbles.onDetachedFromWindow();
        if (runnable != null) {
            mHandler.removeCallbacks(runnable);
        }
    }

    @Override
    public void update(Observable observable, Object data) {
        if (observable != null && observable instanceof MobileChargeColorHelper && data != null
                && data instanceof ChargeColor) {
            ChargeColor chargeColor = (ChargeColor) data;
            int bgColor = chargeColor.getBgViewCurrentColor();
            if (bgColor != 0) {
                setBackgroundColor(bgColor);
            }
            int waveColor1 = chargeColor.getWaveCurrentColor1();
            int waveColor2 = chargeColor.getWaveCurrentColor2();
            if (waveColor1 != 0) {
                wave1.setColor(waveColor1);
            }
            if (waveColor2 != 0) {
                wave2.setColor(waveColor2);
            }
            chargingProgress.update(observable, data);
            invalidate();
        }
    }

    @Override
    public void onScroll(ScrollInfo scrollInfo) {
        removePop();
    }

    @Override
    public void onOpenAd(View slidingView) {
    }

    @Override
    public void onRemove(View v, CardType cardType) {
    }

    @Override
    public void onCardShowAll(View v, CardType cardType) {
    }

    @Override
    public void onCardShowHead(View v, CardType cardType) {
    }

    public void autoShowPopWindow() {
        if (charge == null) {
            return;
        }
        ChargingValueType chargingValueType = charge.getChargingValueType();
        RectF oval;
        if (chargingValueType == ChargingValueType.Speed) {
            oval = getChargingProgress().getOval_1();
        } else if (chargingValueType == ChargingValueType.Continuous) {
            oval = getChargingProgress().getOval_2();
        } else {
            oval = getChargingProgress().getOval_3();
        }
        Float scale = getChargingProgress().getCurrentScale();
        if (scale == 1 && oval != null) {
            initPopupWindow(oval, false);
        }
    }
}
